Cookies do store data locally in the user's browser, but they operate differently from localStorage
. Let's clarify the differences and explore how each can be used, including whether cookies use localStorage
or not.
// Setting a cookie with JavaScript on the client-side
document.cookie = "cart=productId1,productId2,productId3; path=/; expires=Fri, 31 Dec 9999 23:59:59 GMT";
// Reading the cookie
const cartCookie = document.cookie.split('; ').find(row => row.startsWith('cart='));
const cart = cartCookie ? cartCookie.split('=')[1].split(',') : [];
console.log(cart); // ["productId1", "productId2", "productId3"]
In this example, product IDs are stored in a cookie as a comma-separated list. This method has limitations due to the size constraint of cookies and because cookies are sent with every HTTP request, potentially increasing network traffic unnecessarily.
localStorage
is not sent with every HTTP request.// Adding items to localStorage
localStorage.setItem('cart', JSON.stringify(['productId1', 'productId2', 'productId3']));
// Retrieving items from localStorage
const cart = JSON.parse(localStorage.getItem('cart'));
console.log(cart); // ["productId1", "productId2", "productId3"]
In this example, an array of product IDs is stored as a JSON string in localStorage
. This method allows for storing more data than cookies and is more suitable for large or complex data that doesn't need to be sent to the server with every request.
localStorage
is purely client-side storage and not transmitted with HTTP requests.localStorage
is accessible only by client-side scripts.localStorage
persist across browser sessions, but cookies can be set to expire on a specific date.HttpOnly
flag, making them inaccessible via JavaScript and protecting against XSS attacks. localStorage
is accessible through JavaScript, which can be a vector for XSS attacks if the data is not properly handled.Get the latest updates, exclusive content and special offers delivered directly to your mailbox. Subscribe now!